const axios = require('axios');
const config = require('../../config/config');
const { setupLogger } = require('../../utils/logger');

class TwitterService {
  constructor() {
    this.logger = setupLogger();
    this.baseUrl = config.dataSources.twitter.baseUrl;
    this.bearerToken = config.dataSources.twitter.bearerToken;
    this.rateLimitRemaining = 100;
    this.rateLimitReset = Date.now();
  }

  async fetchData() {
    if (!this.bearerToken) {
      this.logger.warn('Twitter Bearer Token未配置，跳过Twitter数据获取');
      return [];
    }

    try {
      this.logger.info('开始获取Twitter数据...');
      
      // 检查速率限制
      if (this.rateLimitRemaining <= 0 && Date.now() < this.rateLimitReset) {
        this.logger.warn('Twitter API速率限制，跳过本次获取');
        return [];
      }

      const data = [];
      
      // 获取加密货币相关推文
      const cryptoTweets = await this.searchTweets('crypto OR bitcoin OR ethereum OR token', 50);
      data.push(...cryptoTweets);
      
      // 获取特定用户的推文（知名加密货币账户）
      const influencerTweets = await this.getUserTweets(['elonmusk', 'VitalikButerin', 'cz_binance'], 20);
      data.push(...influencerTweets);
      
      this.logger.info(`Twitter数据获取完成，共获取 ${data.length} 条数据`);
      return data;
    } catch (error) {
      this.logger.error('Twitter数据获取失败:', error);
      return [];
    }
  }

  async searchTweets(query, maxResults = 50) {
    try {
      const response = await axios.get(`${this.baseUrl}/tweets/search/recent`, {
        headers: {
          'Authorization': `Bearer ${this.bearerToken}`,
          'Content-Type': 'application/json'
        },
        params: {
          query: query,
          max_results: Math.min(maxResults, 100),
          'tweet.fields': 'created_at,author_id,public_metrics,context_annotations,entities',
          'user.fields': 'username,name,verified,public_metrics',
          'expansions': 'author_id'
        }
      });

      this.updateRateLimit(response.headers);
      
      if (!response.data.data) {
        return [];
      }

      const tweets = response.data.data;
      const users = response.data.includes?.users || [];
      const userMap = new Map(users.map(user => [user.id, user]));

      return tweets.map(tweet => {
        const author = userMap.get(tweet.author_id);
        return {
          source: 'twitter',
          type: 'tweet',
          id: tweet.id,
          content: tweet.text,
          author: {
            id: tweet.author_id,
            username: author?.username,
            name: author?.name,
            verified: author?.verified || false,
            followers: author?.public_metrics?.followers_count || 0
          },
          metrics: {
            retweets: tweet.public_metrics?.retweet_count || 0,
            likes: tweet.public_metrics?.like_count || 0,
            replies: tweet.public_metrics?.reply_count || 0,
            quotes: tweet.public_metrics?.quote_count || 0
          },
          entities: tweet.entities,
          contextAnnotations: tweet.context_annotations,
          createdAt: tweet.created_at,
          timestamp: new Date().toISOString()
        };
      });
    } catch (error) {
      if (error.response?.status === 429) {
        this.logger.warn('Twitter API速率限制');
        this.rateLimitRemaining = 0;
        this.rateLimitReset = Date.now() + 15 * 60 * 1000; // 15分钟后重置
      }
      throw error;
    }
  }

  async getUserTweets(usernames, maxResults = 20) {
    const allTweets = [];
    
    for (const username of usernames) {
      try {
        // 首先获取用户ID
        const userResponse = await axios.get(`${this.baseUrl}/users/by/username/${username}`, {
          headers: {
            'Authorization': `Bearer ${this.bearerToken}`,
            'Content-Type': 'application/json'
          },
          params: {
            'user.fields': 'username,name,verified,public_metrics'
          }
        });

        if (!userResponse.data.data) {
          continue;
        }

        const user = userResponse.data.data;
        
        // 获取用户推文
        const tweetsResponse = await axios.get(`${this.baseUrl}/users/${user.id}/tweets`, {
          headers: {
            'Authorization': `Bearer ${this.bearerToken}`,
            'Content-Type': 'application/json'
          },
          params: {
            max_results: Math.min(maxResults, 100),
            'tweet.fields': 'created_at,public_metrics,context_annotations,entities',
            exclude: 'retweets,replies'
          }
        });

        this.updateRateLimit(tweetsResponse.headers);

        if (tweetsResponse.data.data) {
          const tweets = tweetsResponse.data.data.map(tweet => ({
            source: 'twitter',
            type: 'user_tweet',
            id: tweet.id,
            content: tweet.text,
            author: {
              id: user.id,
              username: user.username,
              name: user.name,
              verified: user.verified || false,
              followers: user.public_metrics?.followers_count || 0
            },
            metrics: {
              retweets: tweet.public_metrics?.retweet_count || 0,
              likes: tweet.public_metrics?.like_count || 0,
              replies: tweet.public_metrics?.reply_count || 0,
              quotes: tweet.public_metrics?.quote_count || 0
            },
            entities: tweet.entities,
            contextAnnotations: tweet.context_annotations,
            createdAt: tweet.created_at,
            timestamp: new Date().toISOString()
          }));
          
          allTweets.push(...tweets);
        }
        
        // 避免过快请求
        await this.delay(1000);
      } catch (error) {
        this.logger.error(`获取用户 ${username} 推文失败:`, error.message);
        continue;
      }
    }
    
    return allTweets;
  }

  updateRateLimit(headers) {
    if (headers['x-rate-limit-remaining']) {
      this.rateLimitRemaining = parseInt(headers['x-rate-limit-remaining']);
    }
    if (headers['x-rate-limit-reset']) {
      this.rateLimitReset = parseInt(headers['x-rate-limit-reset']) * 1000;
    }
  }

  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  getRateLimitStatus() {
    return {
      remaining: this.rateLimitRemaining,
      resetTime: new Date(this.rateLimitReset).toISOString()
    };
  }
}

module.exports = new TwitterService();

